<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\PdfController;
use App\Http\Controllers\ScoreRuleController;
use App\Http\Controllers\ZipFileDownloadController;
use App\Models\ContestActivity;
use App\Models\ContestActivityType;
use App\Models\ContestActivityUnit;
use App\Models\ContestActivityWorks;
use App\Models\UserInfo;
use App\Validate\ContestActivityValidate;
use Exception;
use Illuminate\Support\Facades\DB;

/**
 * 线上大赛作品
 */
class ContestActivityWorksController extends CommonController
{

    public $score_type = 7;
    public $model = null;
    public $contestActivityModel = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new ContestActivityWorks();
        $this->contestActivityModel = new ContestActivity();
        $this->validate = new ContestActivityValidate();
    }

    /**
     * 列表
     * @param page int 当前页
     * @param limit int 分页大小
     * @param con_id int 大赛id
     * @param unit_id int 大赛单位id  多馆联合活动才有
     * @param status int 是否审核 状态  1.已通过   2.未通过   3.未审核(默认)   不传为全部
     * @param type_id int 类型id
     * @param keywords string 搜索关键词(作品名称|姓名|编号)
     * @param start_time datetime 投稿时间(开始)
     * @param end_time datetime 投稿时间(截止)
     * @param sort int 排序方式  1 时间排序（默认）  2 投票排序
     */
    public function lists()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('production_list')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $con_id = $this->request->con_id;
        $unit_id = $this->request->unit_id;
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;
        $keywords = $this->request->keywords;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $status = $this->request->status;
        $type_id = $this->request->type_id;
        $sort = $this->request->input('sort', '1');
        $sort = $sort == 2 ? 'vote_num DESC,id ASC' : 'id ASC'; //vote_num ASC,id ASC 解决点赞量全为0时，数据错乱问题

        $status = empty($status) ? [1, 2, 3] : [$status];
        $res = $this->model->lists($con_id, $unit_id, null, $type_id, $keywords,  $status, '', $start_time, $end_time, $sort, $limit);

        if (empty($res['data'])) {
            return $this->returnApi(203, "暂无数据");
        }

        $contestActivityUnitModel = new ContestActivityUnit();
        $ids = [];
        foreach ($res['data'] as $key => $val) {
            $ids[] = $val['id'];
            $res['data'][$key][$this->list_index_key] = $this->addSerialNumberOne($key, $page, $limit);
            $res['data'][$key]['type_name'] = ContestActivityType::where('id', $val['type_id'])->value('type_name');
            $res['data'][$key]['head_img'] = UserInfo::getWechatField($val['user_id'], 'head_img');

            $res['data'][$key]['unit_name'] = !empty($val['unit_id']) ? $contestActivityUnitModel->getUnitNameByUnitId($val['unit_id']) : '';
        }

        $this->model->where('con_id', $con_id)->whereIn('id', $ids)->update(['is_look' => 1]);

        $res = $this->disPageData($res);

        //获取总投票量
        $res['total_vote_num'] = $this->model->getTotalVoteNumber($con_id);

        return $this->returnApi(200, "查询成功", "YES", $res);
    }

    /**
     * 详情
     * @param id int 作品id
     * 
     * //用户获取下一个作品
    //  * @param con_id int 大赛id
    //  * @param unit_id int 单位id
    //  * @param type_id int 类型id
     * //@param status int 是否审核 状态  1.已通过   2.未通过   3.未审核(默认)   不传为全部
     * @param keywords string 搜索关键词(作品名称|姓名|编号)
     * @param start_time datetime 投稿时间(开始)
     * @param end_time datetime 投稿时间(截止)
     * @param sort int 排序方式  1 时间排序（默认）  2 投票排序
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('production_detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        //用于获取下一个作品
        $keywords = $this->request->keywords;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        //  $status = $this->request->status;
        // $con_id = $this->request->con_id;
        // $type_id = $this->request->type_id;
        // $unit_id = $this->request->unit_id;
        $sort = $this->request->input('sort', '1');
        $sort = $sort == 2 ? 'vote_num DESC,id ASC' : 'id ASC'; //vote_num ASC,id ASC 解决点赞量全为0时，数据错乱问题

        $res = $this->model->detail($this->request->id);
        if (empty($res)) {
            return $this->returnApi(203, "暂无数据");
        }

        $res['head_img'] = UserInfo::getWechatField($res['user_id'], 'head_img');
        //获取下一个未审核的活动
        $res->next_data = $this->model->getNextUnchecked($res->con_id, $this->request->id, $res->unit_id, $res->type_id, $keywords, $start_time, $end_time, $sort);

        $contestActivityModel = new ContestActivity();
        $real_info = $contestActivityModel->where('id', $res->con_id)->value('real_info');
        $real_info_array = $contestActivityModel->getContestActivityApplyParam();

        $res->real_info_value = $this->getRealInfoArray($real_info, $real_info_array, 'value');
        $res->real_info_value = join("|", $res->real_info_value);

        // if ($real_info) {
        //     $real_info = explode("|", $real_info);
        //     $real_info_value = [];
        //     foreach ($real_info as $key => $val) {
        //         $temp = isset($real_info_array[$val - 1]) ? $real_info_array[$val - 1]['value'] : '';
        //         $real_info_value[] = $temp;
        //     }
        //     $res->real_info_value = implode("|", $real_info_value);
        // } else {
        //     $res->real_info_value = null;
        // }

        $contestActivityUnitModel = new ContestActivityUnit();
        $res['unit_name'] = $contestActivityUnitModel->getUnitNameByUnitId($res['unit_id']);
        $res = $this->disDataSameLevel($res->toArray(), 'con_type', ['type_name' => 'type_name']);

        return $this->returnApi(200, "获取成功", true, $res);
    }

    /**
     * 审核作品
     * @param id int 作品id
     * @param status int 状态    1.通过   2.未通过
     * @param reason string 拒绝原因
     */
    public function worksCheck()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('works_check')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $id = $this->request->id;
        $status = $this->request->status;
        $reason = $this->request->reason ? $this->request->reason : null;

        if ($status == 2 && !$reason) {
            return $this->returnApi(202, '请填写拒绝原因');
        }

        $works = $this->model->find($id);
        $old_status =  $works->status;
        if (!$works) {
            return $this->returnApi(202, '参数传递错误');
        }
        // if ($works->status != 3) {
        //     return $this->returnApi(202, '当前作品审核状态有误');
        // }

        $works->status = $status;
        $works->reason = $reason;

        DB::beginTransaction();
        try {
            /*消息推送*/
            $check_msg = $works->status == 1 ? '审核通过' : '审核未通过';
            if ($works->status == 1) {
                $system_id = $this->systemAdd('线上大赛：您投稿的作品' . $check_msg, $works->user_id, $works->account_id, 17, intval($works->id), '作品：【' . $works->title . '】' . $check_msg);
            } else {
                $system_id = $this->systemAdd('线上大赛：您投稿的作品' . $check_msg, $works->user_id, $works->account_id, 17, intval($works->id), '作品：【' . $works->title . '】' . $check_msg . '，拒绝理由为：' . $this->request->reason);
            }

            /**执行积分规则 */
            //如果现在状态不是待审核，都不管积分，积分统一采用审核时操作，
            if ($old_status == 3 && $status == 1) {
                // $scoreRuleObj = new ScoreRuleController();
                // $score_msg = $scoreRuleObj->getScoreMsg($works->score);
                // $scoreRuleObj->scoreReturn(7, $works->score, $works->user_id, $works->account_id, $check_msg . '，' . $score_msg . ' ' . abs($works->score) . ' 积分', $system_id);

                $is_reader = ContestActivity::where('id', $works->con_id)->value('is_reader');
                if (config('other.is_need_score') === true  && $is_reader == 1) {
                    $scoreRuleObj = new ScoreRuleController();
                    $score_status = $scoreRuleObj->checkScoreStatus($this->score_type, $works->user_id, $works->account_id);
                    if ($score_status['code'] == 202 || $score_status['code'] == 203) throw new Exception($score_status['msg']);
                    if ($score_status['code'] == 200) {
                        $scoreRuleObj->scoreChange($score_status, $works->user_id, $works->account_id, $system_id); //添加积分消息
                    }
                }
            }

            $works->save();

            $check_msg = $works->status == 1 ? '已通过' : '已拒绝';

            DB::commit();
            return $this->returnApi(200, $check_msg, true);
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 违规 与 取消违规操作
     * @param id int 申请id
     * @param reason string 违规原因
     */
    public function violateAndCancel()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('violate_and_cancel')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }

        // 启动事务
        DB::beginTransaction();
        try {
            $res = $this->model->violateAndCancel($this->request->id, $this->request->reason);

            /*消息推送*/
            if ($res->is_violate == 2) {
                $system_id = $this->systemAdd('在线投票作品已违规', $res->user_id, $res->account_id, 60, $res->id, '您发布的在线投票作品：【' . $res->title . '】已违规，违规理由为：' . $this->request->reason);

                // if (!empty($res->score)) {
                //     $score_rule = new ScoreRuleController();
                //     $score_msg = $score_rule->getScoreMsg($res->score);
                //     $score_rule->scoreReturn($this->score_type, $res->score, $res->user_id, $res->account_id, '在线投票作品已违规，' . $score_msg . ' ' . abs($res->score) . ' 积分', $system_id);
                // }
            } else {
                $system_id = $this->systemAdd('在线投票作品已取消违规', $res->user_id, $res->account_id, 60, $res->id, '您发布的在线投票作品：【' . $res->title . '】已取消违规');

                // if (!empty($res->score)) {
                //     $score_rule = new ScoreRuleController();
                //     $score_msg = $score_rule->getScoreMsg(-$res->score); //相反积分
                //     $score_rule->scoreReturn($this->score_type, $res->score, $res->user_id, $res->account_id, '在线投票作品已取消违规，' . $score_msg . ' ' . abs($res->score) . ' 积分', $system_id);
                // }
            }

            // 提交事务
            DB::commit();
            return $this->returnApi(200, "操作成功", true);
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 单个下载作品
     * @param id int 作品id
     */
    public function downloadWorks()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('production_list_download_img')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $id = $this->request->id;
        $field = [
            'id', 'con_id', 'serial_number', 'img','title', 'content', 'voice', 'voice_name', 'video', 'video_name', 'intro'
        ];
        $res = $this->model->detail($id, $field);
        if (empty($res)) {
            return $this->returnApi(203, "暂无数据");
        }
        $res = $res->toArray();
        $zipFileDownloadObj = new ZipFileDownloadController();
        $file_name = ContestActivity::where('id', $res['con_id'])->value('title');
        //图片作品生成pdf文件
        $path_arr[] = $this->model->disData($res, $file_name);
        $zip_path = $zipFileDownloadObj->addPackage($path_arr, null, $res['serial_number'] . '-在线投票作品下载-' . date('Y-m-d'), 10); //缓存时间长了，筛选数据还是之前的
        return response()->download($zip_path);
    }

    /**
     * 批量下载作品
     * @param con_id int 大赛id
     * @param unit_id int 大赛单位id  多馆联合活动才有
     * @param status int 是否审核 状态  1.已通过   2.未通过   3.未审核(默认)   不传为全部
     * @param type_id int 类型id
     * @param keywords string 搜索关键词(作品名称|姓名|编号)
     * @param start_time datetime 投稿时间(开始)
     * @param end_time datetime 投稿时间(截止)
     */
    public function downloadWorksAll()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('production_list_download_img_all')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $con_id = $this->request->con_id;
        $unit_id = $this->request->unit_id;
        $keywords = $this->request->keywords;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $status = $this->request->status;
        $type_id = $this->request->type_id;

        $status = empty($status) ? [1, 2, 3] : [$status];
        $res = $this->model->lists($con_id, $unit_id, null, $type_id, $keywords,  $status, '', $start_time, $end_time, 'id desc', 99999);
        if (empty($res['data'])) {
            return $this->returnApi(203, "暂无数据");
        }

        $zipFileDownloadObj = new ZipFileDownloadController();
        $path_arr = [];
        $file_name = ContestActivity::where('id', $con_id)->value('title');
        //图片作品生成pdf文件
        foreach ($res['data'] as $key => $val) {
            $path_arr[$key] = $this->model->disData($val, $file_name);
        }
        $zip_path = $zipFileDownloadObj->addPackage($path_arr, null, $file_name . '-在线投票作品下载-' . date('Y-m-d'), 10); //缓存时间长了，筛选数据还是之前的
        return response()->download($zip_path);
    }
}
